from __future__ import with_statement
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from django.utils import simplejson as json
import re

from CyworldUrl import CyworldUrl
import swiffy

class MainHandler(webapp.RequestHandler):
    def get(self):
        self._convert(self.request.GET) if self.request.GET.has_key('url') else self.redirect("/static/index.html")
        
    def post(self):
        self._convert(self.request.POST)
        
    def _convert(self, param): 
        callback = param['callback'] if param.has_key('callback') else None
        swf = CyworldUrl().open(param['url']).read()
        result = json.dumps(swiffy.convert_swf_to_images(swf))
        self.response.out.write(result if not callback else '%s(%s)' % (callback, result))
        
class DiscoverHandler(webapp.RequestHandler):
    def get(self):
        html = CyworldUrl().open(self.request.get('url')).read()
        m = re.search(r'flashPath="(.*.swf)"', html)
        if m is None:
            self.error(500)
        else:
            self.response.out.write(json.dumps({'swfUrl': m.group(1)}))
            
def main(): 
    run_wsgi_app(webapp.WSGIApplication([('/', MainHandler), ('/discover', DiscoverHandler)], debug=True))

if __name__ == '__main__':
    main()
